package com.pybox.spec;

import com.pybox.entity.TUserMenu;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
* 描述：TUserMenu Specification
* @author wuyingkai
* @date 2018-09-15
*/


public class TUserMenuSpec implements Specification<TUserMenu> {

    private Map<String, String> params;

    public TUserMenuSpec(Map<String, String> params){
        this.params = params;
    }

    @Override
    public Predicate toPredicate(Root<TUserMenu> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {

        String userId = this.params.get("userId");
        String menuId = this.params.get("menuId");
        List<Predicate> ps = new ArrayList<>();

        if (!StringUtils.isEmpty(userId)) {
            ps.add(criteriaBuilder.like(root.get("userId"), "%" + userId + "%"));
        }
        if (!StringUtils.isEmpty(menuId)) {
            ps.add(criteriaBuilder.like(root.get("menuId"), "%" + menuId + "%"));
        }

        criteriaQuery = criteriaQuery.where(ps.toArray(new Predicate[ps.size()]));

        return criteriaQuery.getRestriction();
    }

}